package com.lyx.controller;


import com.alibaba.fastjson.JSON;
import com.lyx.entity.Menu;
import com.lyx.response.Result;
import com.lyx.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;

import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author com.lyx
 * @since 2022-03-02
 */
@CrossOrigin
@Api(tags = "菜单控制器")
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    MenuService menuService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @ApiOperation(value = "加载菜单树", notes = "获取所有菜单树，以及展开项")
    @GetMapping("/tree")
    public Result tree() {
        //定义一个存放菜单栏的键
         String key= "menuTree";

        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        List<Menu> menuTree =null ;
        //判断是否存在这个key
        if (!redisTemplate.hasKey(key)){
             menuTree = menuService.findMenuTree();
            //并且需要往redis存一份
            ops.set(key,menuTree);
        }else {
            Object o = ops.get(key);
            //需要拆箱
             menuTree = JSON.parseObject(JSON.toJSONString(o), ArrayList.class);
        }
        //jdk8 流的新特性
    //   List<Integer> ids = menuTree.stream().map(menu-> menu.getOpen()).collect(Collectors.toList());
        return Result.ok().data("tree",menuTree);//.data("open",ids);
    }

}

